<template>
  <div class="comment-panel rounded-2xl p-0 border border-slate-100 shadow-sm bg-white">
    <div class="flex justify-between items-center px-6 pt-4 pb-2">
      <div class="font-bold text-base text-slate-800">{{ (comments?.length || 0) + '条评论' }}</div>
      <slot name="actions"></slot>
    </div>
    <!-- 评论列表 -->
    <div class="px-6 pb-4">
      <div
        v-if="comments && comments.length"
        class="comment-list-box"
      >
        <div v-for="comment in displayComments" :key="comment.id" class="comment-item flex gap-3 items-start py-4 border-b last:border-b-0 border-slate-100" :class="{'adopted-comment': comment.isAdopted}">
          <img :src="comment.avatar" class="w-9 h-9 rounded-full object-cover shadow-sm" />
          <div class="flex-1 min-w-0">
            <div class="flex items-center justify-between mb-0.5">
              <div class="flex items-center gap-1 min-h-[36px]">
                <!-- <UserHoverCard :user="getUser(comment.author)">
                  <span class="text-xs text-blue-600 font-medium cursor-pointer hover:underline">{{ comment.author }}</span>
                </UserHoverCard> -->
                <template v-if="comment.replyTo">
                  <span class="mx-0.5 flex items-center">
                    <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg" style="display:inline-block;vertical-align:middle;"><polygon points="4,2 9,6 4,10" fill="#b0b8c9"/></svg>
                  </span>
                  <!-- <UserHoverCard :user="getUser(comment.replyTo)">
                    <span class="text-xs text-blue-600 font-medium cursor-pointer hover:underline">{{ comment.replyTo }}</span>
                  </UserHoverCard> -->
                </template>
                
                <span v-if="comment.isAuthor" class="text-xs bg-blue-50 text-blue-600 rounded px-1 ml-1">作者</span>
              </div>
              <el-dropdown
                trigger="click"
                popper-class="comment-more-dropdown"
                placement="bottom-end"
              >
                <span class="more-btn flex items-center justify-center">
                  <el-icon><MoreFilled /></el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="showReportDialog(comment)">举报</el-dropdown-item>
                    <el-dropdown-item 
                      v-if="!hasAdoptedComment && !comment.isAdopted"
                      @click="confirmAdopt(comment)"
                    >采纳</el-dropdown-item>
                    <el-dropdown-item v-else-if="comment.isAdopted" disabled>
                      <el-icon class="adopted-icon"><Check /></el-icon>已采纳
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
            <div class="text-slate-800 text-[15px] leading-relaxed mb-1">
              <div v-if="comment.isAdopted" class="adopted-badge">
                <el-icon><Check /></el-icon>
                已采纳
              </div>
              {{ comment.content }}
            </div>
            <div class="comment-actions flex gap-6 items-center justify-end mt-1">
              <span class="text-xs text-slate-400 min-w-[110px] mr-auto">{{ comment.time }} · {{ comment.region || '山东' }}</span>
              <span class="cursor-pointer hover:text-blue-500 flex items-center gap-1" @click="startReply(comment)"><el-icon class="icon"><ChatDotRound /></el-icon>回复</span>
              <span class="like-btn cursor-pointer flex items-center gap-1" :class="comment.liked ? 'text-pink-600 font-bold' : 'text-gray-400'" @click="onLikeComment(comment)"><svg class="w-4 h-4 icon" fill="currentColor" viewBox="0 0 20 20"><path d="M3.172 5.172a4 4 0 015.656 0L10 6.343l1.172-1.171a4 4 0 115.656 5.656L10 17.657l-6.828-6.829a4 4 0 010-5.656z"/></svg>{{ comment.likeCount || 0 }}</span>
            </div>
            <ExpertCommentInput
              v-if="replyingTo && replyingTo.commentId === comment.id && !replyingTo.replyId"
              v-model="replyInput"
              :user-avatar="userAvatar"
              :placeholder="`回复 ${comment.author}`"
              :loading="replyLoading"
              @submit="val => submitReply(comment, val)"
              class="mt-2 w-[260px]"
            />
            <!-- 回复区 -->
            <div v-if="comment.replies && comment.replies.length" class="reply-list-box">
              <div v-for="(reply, ridx) in isRepliesExpanded(comment.id) ? comment.replies : comment.replies.slice(0,2)" :key="reply.id" class="reply-item flex gap-2 items-start py-2 border-b last:border-b-0 border-slate-100">
                <img :src="reply.avatar" class="w-7 h-7 rounded-full object-cover shadow-sm" />
                <div class="flex-1 min-w-0">
                  <div class="flex items-center justify-between mb-0.5">
                    <div class="flex items-center gap-1 min-h-[28px]">
                      <!-- <UserHoverCard :user="getUser(reply.author)" small>
                        <span class="text-xs text-blue-600 font-medium cursor-pointer hover:underline">{{ reply.author }}</span>
                      </UserHoverCard> -->
                      <span v-if="reply.replyTo" class="mx-0.5 flex items-center">
                          <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg" style="display:inline-block;vertical-align:middle;"><polygon points="4,2 9,6 4,10" fill="#b0b8c9"/></svg>
                        </span>
                        <!-- <UserHoverCard v-if="reply.replyTo" :user="getUser(reply.replyTo)">
                          <span class="text-xs text-blue-600 font-medium cursor-pointer hover:underline">{{ reply.replyTo }}</span>
                        </UserHoverCard> -->
                    </div>
                    <el-dropdown
                      trigger="click"
                      popper-class="comment-more-dropdown"
                      placement="bottom-end"
                    >
                      <span class="more-btn flex items-center justify-center">
                        <el-icon><MoreFilled /></el-icon>
                      </span>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item @click="showReportDialog(reply, comment)">举报</el-dropdown-item>
                          <el-dropdown-item 
                            v-if="!hasAdoptedComment && !reply.isAdopted"
                            @click="confirmAdopt(reply, comment)"
                          >采纳</el-dropdown-item>
                          <el-dropdown-item v-else-if="reply.isAdopted" disabled>
                            <el-icon class="adopted-icon"><Check /></el-icon>已采纳
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                  <div class="text-slate-800 text-[15px] leading-relaxed mb-1">
                    <div v-if="reply.isAdopted" class="adopted-badge">
                      <el-icon><Check /></el-icon>
                      已采纳
                    </div>
                    {{ reply.content }}
                  </div>
                  <div class="reply-actions flex gap-6 items-center justify-end mt-1">
                    <span class="text-xs text-slate-400 min-w-[110px] mr-auto">{{ reply.time }} · {{ reply.region || '北京' }}</span>
                    <span class="cursor-pointer hover:text-blue-500 flex items-center gap-1" @click="startReply(comment, reply)"><el-icon class="icon"><ChatDotRound /></el-icon>回复</span>
                    <span class="like-btn cursor-pointer flex items-center gap-1" :class="reply.liked ? 'text-pink-600 font-bold' : 'text-gray-400'" @click="onLikeReply(comment, reply)"><svg class="w-4 h-4 icon" fill="currentColor" viewBox="0 0 20 20"><path d="M3.172 5.172a4 4 0 015.656 0L10 6.343l1.172-1.171a4 4 0 115.656 5.656L10 17.657l-6.828-6.829a4 4 0 010-5.656z"/></svg>{{ reply.likeCount || 0 }}</span>
                  </div>
                  <ExpertCommentInput
                    v-if="replyingTo && replyingTo.commentId === comment.id && replyingTo.replyId === reply.id"
                    v-model="replyInput"
                    :user-avatar="userAvatar"
                    :placeholder="`回复 ${reply.author}`"
                    :loading="replyLoading"
                    @submit="val => submitReply(comment, val, reply)"
                    class="mt-2 w-[220px]"
                  />
                </div>
              </div>
              <div v-if="!isRepliesExpanded(comment.id) && comment.replies.length > 2" class="text-center mt-2">
                <span class="expand-replies-btn" @click="openReplyDialog(comment)">查看全部 {{ comment.replies.length }} 条回复</span>
              </div>
            </div>
          </div>
        </div>
        <div v-if="showViewAllBtn" class="text-center py-2">
          <span class="text-blue-500 cursor-pointer text-xs hover:underline" @click="handleViewAll">点击查看全部评论</span>
        </div>
      </div>
      <div v-else class="text-slate-400 text-center py-4">暂无评论内容</div>
    </div>
  </div>

  <!-- 举报对话框 -->
  <ReportDialog
    v-model="reportDialogVisible"
    :report-info="reportInfo"
    @success="handleReportSuccess"
  />

  <!-- 采纳确认对话框 -->
  <el-dialog
    v-model="adoptConfirmVisible"
    title="采纳确认"
    width="400px"
    :close-on-click-modal="false"
  >
    <div class="adopt-confirm-content">
      <p class="text-gray-600 mb-4">确定要采纳这条回答吗？</p>
      <p class="text-gray-500 text-sm">采纳后：</p>
      <ul class="text-gray-500 text-sm list-disc list-inside mb-4">
        <li>该回答将被标记为最佳答案</li>
        <li>问题将被标记为已解决</li>
        <li>采纳后无法更改</li>
      </ul>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="adoptConfirmVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAdopt" :loading="adoptLoading">
          确认采纳
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ChatDotRound, MoreFilled, Check } from '@element-plus/icons-vue'
import ExpertCommentInput from './ExpertCommentInput.vue'
// import UserHoverCard from './UserHoverCard.vue'
import ReportDialog from './commonUI/ReportDialog.vue'
import { ElMessage } from 'element-plus'
const props = defineProps({
  comments: Array,
  userAvatar: String,
  showAll: {
    type: Boolean,
    default: false
  },
  onViewAll: Function // 父组件传递的弹窗打开方法
})
const emit = defineEmits(['like-comment', 'like-reply', 'reply-comment', 'reply-reply', 'open-reply-dialog', 'adopt'])
const replyInput = ref('')
const replyLoading = ref(false)
const replyingTo = ref(null) // {commentId, replyId}
const expandedReplyMap = ref({})

const displayComments = computed(() => {
  if (props.showAll) return props.comments || []
  return props.comments ? props.comments.slice(0, 10) : []
})
const showViewAllBtn = computed(() => {
  return !props.showAll && (props.comments?.length >= 10) && typeof props.onViewAll === 'function'
})  
function handleViewAll() {
  if (props.onViewAll) props.onViewAll()
}

function startReply(comment, reply) {
  replyingTo.value = { commentId: comment.id, replyId: reply ? reply.id : null }
  replyInput.value = ''
}
function cancelReply() {
  replyingTo.value = null
  replyInput.value = ''
}
async function submitReply(comment, val, reply) {
  if (!val.trim()) return
  replyLoading.value = true
  await emit('reply-reply', { commentId: comment.id, replyId: replyingTo.value.replyId, content: val })
  replyInput.value = ''
  replyingTo.value = null
  replyLoading.value = false
}
function onLikeComment(comment) {
  emit('like-comment', comment)
}
function onLikeReply(comment, reply) {
  emit('like-reply', { comment, reply })
}
function expandReplies(commentId) {
  expandedReplyMap.value[commentId] = true
}
function isRepliesExpanded(commentId) {
  return props.showAll || expandedReplyMap.value[commentId]
}

// mock 用户数据
const userMap = {
  '匿名用户': {
    name: '匿名用户',
    avatar: 'https://randomuser.me/api/portraits/lego/1.jpg',
    desc: '热心网友',
    answer: 12,
    article: 0,
    follower: 5,
    uid: 1001,
    id: 1001
  },
  '浩轩': {
    name: '浩轩',
    avatar: 'https://randomuser.me/api/portraits/men/32.jpg',
    desc: '玩家',
    answer: 64,
    article: 0,
    follower: 33,
    uid: 1002,
    id: 1002
  },
  '知乎用户': {
    name: '知乎用户',
    avatar: 'https://randomuser.me/api/portraits/lego/2.jpg',
    desc: '知乎活跃用户',
    answer: 8,
    article: 1,
    follower: 12,
    uid: 1003,
    id: 1003
  },
  '你': {
    name: '你',
    avatar: 'https://randomuser.me/api/portraits/lego/3.jpg',
    desc: '本地测试',
    answer: 0,
    article: 0,
    follower: 0,
    uid: 1004,
    id: 1004
  }
}
function getUser(name) {
  return userMap[name] || {
    name,
    avatar: 'https://randomuser.me/api/portraits/lego/4.jpg',
    desc: '普通用户',
    answer: 0,
    article: 0,
    follower: 0,
    uid: 9999,
    id: 9999
  }
}

// 打开回复弹窗
function openReplyDialog(comment) {
  emit('open-reply-dialog', comment, (page, pageSize) => {
    // 模拟分页，真实项目应请求后端
    const total = comment.replies.length
    const start = (page - 1) * pageSize
    const end = start + pageSize
    return Promise.resolve({
      list: comment.replies.slice(start, end),
      total
    })
  })
}

// 举报相关
const reportDialogVisible = ref(false)
const reportInfo = ref({})

function showReportDialog(item, parentComment = null) {
  reportInfo.value = {
    type: parentComment ? 'reply' : 'comment',
    id: item.id,
    content: item.content,
    author: item.author,
    parentId: parentComment?.id
  }
  reportDialogVisible.value = true
}

function handleReportSuccess(data) {
  console.log('举报成功:', data)
}

// 采纳相关
const adoptConfirmVisible = ref(false)
const adoptLoading = ref(false)
const currentAdoptItem = ref(null)
const currentAdoptParent = ref(null)

const hasAdoptedComment = computed(() => {
  if (!props.comments) return false
  return props.comments.some(comment => {
    if (comment.isAdopted) return true
    return comment.replies?.some(reply => reply.isAdopted)
  })
})

function confirmAdopt(item, parentComment = null) {
  currentAdoptItem.value = item
  currentAdoptParent.value = parentComment
  adoptConfirmVisible.value = true
}

async function handleAdopt() {
  if (!currentAdoptItem.value) return
  
  try {
    adoptLoading.value = true
    
    // TODO: 调用采纳API
    await new Promise(resolve => setTimeout(resolve, 1000)) // 模拟API调用
    
    // 更新状态
    currentAdoptItem.value.isAdopted = true
    
    // 发送事件通知父组件更新问题状态
    emit('adopt', {
      item: currentAdoptItem.value,
      parent: currentAdoptParent.value
    })
    
    ElMessage.success('采纳成功')
    adoptConfirmVisible.value = false
    
  } catch (error) {
    console.error('采纳失败:', error)
    ElMessage.error('采纳失败，请稍后重试')
  } finally {
    adoptLoading.value = false
  }
}
</script>
<style scoped>
.comment-panel {
  background: #fff;
  border-radius: 1.5rem;
  box-shadow: 0 2px 12px 0 rgba(56,112,255,0.06);
  border: 1px solid #e5eaf3;
}
.comment-list-box {
  background: #fff;
  border-radius: 1.2rem;
  box-shadow: 0 1px 6px 0 rgba(56,112,255,0.04);
  border: 1px solid #f0f3fa;
}
.comment-item {
  align-items: flex-start;
  gap: 14px;
  padding-left: 2px;
}
.reply-list-box {
  background: #f6faff;
  border-radius: 1.2rem;
  border: 1px solid #e5eaf3;
  box-shadow: 0 1px 4px 0 rgba(56,112,255,0.06);
  margin-top: 8px;
  padding: 12px 18px 8px 18px;
}
.reply-item {
  align-items: flex-start;
  gap: 10px;
  border-bottom: 1px solid #e5eaf3;
  padding-bottom: 8px;
  margin-bottom: 2px;
}
.reply-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}
.comment-actions, .reply-actions {
  display: flex;
  gap: 18px;
  align-items: center;
  font-size: 14px;
  color: #8a99b3;
  margin-top: 2px;
}
.comment-actions .icon, .reply-actions .icon {
  font-size: 15px;
  margin-right: 2px;
}
.comment-actions .like-btn {
  display: flex;
  align-items: center;
  gap: 2px;
  margin-right: 19px;
}
.reply-actions .like-btn {
  margin-right: 0;
}
.expand-replies-btn {
  color: #409eff;
  background: #f0f6ff;
  border-radius: 8px;
  padding: 3px 14px;
  font-size: 13px;
  margin-top: 6px;
  cursor: pointer;
  display: inline-block;
  transition: background 0.15s;
}
.expand-replies-btn:hover {
  background: #e0edff;
}
.more-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #bdbdbd;
  cursor: pointer;
  font-size: 18px;
  height: 36px;
  width: 36px;
  vertical-align: middle;
  margin-right: 13px;
}
.reply-item .more-btn {
  height: 28px;
  width: 28px;
  margin-right: 0;
}
.adopted-comment {
  background-color: #f8faff;
  border-radius: 8px;
  border: 1px solid #e6efff !important;
}
.adopted-badge {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  background-color: #ecf5ff;
  color: #409eff;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  margin-bottom: 8px;
}
.adopted-icon {
  color: #67c23a;
  font-size: 14px;
  margin-right: 2px;
}
.adopt-confirm-content {
  padding: 0 20px;
}
:deep(.el-dialog__header) {
  border-bottom: 1px solid #f0f0f0;
  margin-right: 0;
  padding: 20px;
}
:deep(.el-dialog__footer) {
  border-top: 1px solid #f0f0f0;
  padding: 20px;
}
:deep(.el-dialog__body) {
  padding: 24px 0;
}
</style> 